#include "oGamePreDefine.h"
#include "oPokeAction.h"
#include "oGameTypes.h"

oPokeAction::oPokeAction( oUnit* owner ):
oAction(ACTION_POKE, 0, owner),
_current(0.0f),
_isBooming(false),
_count(0)
{ }

void oPokeAction::update( ccTime dt )
{
	float vx = _owner->getVelocityX();
	if (!_isBooming)
	{
		if (-50.0f <= vx && vx <= 50.0f)
		{
			_isBooming = true;
			oFrameActionDef* def;
			if (_owner->getGroup() == GROUP_POKE_ME)
			{
				def = oSharedAnimationCache.load("poke.frame");
			}
			else
			{
				def = oSharedAnimationCache.load("poke_enemy.frame");
			}
			CCSprite* sprite = (CCSprite*)_owner->getChildren()->objectAtIndex(1);
			oFrame* frame = def->toAction();
			frame->setLoop(true);
			sprite->runAction(frame);
			SimpleAudioEngine::sharedEngine()->playEffect("sound/di.wav");
		}
	}
	else if (_count < 5)
	{
		_current += dt;
		if (_current >= 0.5f)
		{
			_current = 0.0f;
			_count++;
			if (_count == 5)
			{
				_owner->attach(oBodyDef::circleSensor(BoomSensorTag, 400));
			}
			SimpleAudioEngine::sharedEngine()->playEffect("sound/di.wav");
		}
	}
	else
	{
		oSensor* sensor = _owner->getSensorByTag(BoomSensorTag);
		BOOST_FOREACH(oBody* body, sensor->getSensedBodies())
		{
			if (oSharedData.isPlayerUnit(body))
			{
				oUnit* unit = (oUnit*)body;
				oHit* hitAction = (oHit*)unit->getAction(oID::ActionHit);
				if (hitAction)
				{
					bool right = unit->getPositionX() < _owner->getPositionX();
					hitAction->setHitInfo(CCPointZero, CCPoint(1000.0f, 1200.0f), right);
				}
				unit->hp -= 1;
			}
		}
		oEffect* effect = oSharedEffectCache.create(EFFECT_POKEBOOM);
		effect->attachTo(_owner->getWorld(), LAYER_FOREGROUND_ID)->setOffset(_owner->getPosition())->autoRemove()->start();
		effect->getNode()->setScale(3.0f);
		_owner->destroy();
		SimpleAudioEngine::sharedEngine()->playEffect("sound/explosion.wav");
	}
}
